package wangxiaotao.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import wangxiaotao.aop.annotation.Log;
import wangxiaotao.bean.vo.RoomVO;
import wangxiaotao.common.CommonResult;
import wangxiaotao.converter.RoomConverter;
import wangxiaotao.entity.Room;
import wangxiaotao.enums.RoomStatue;
import wangxiaotao.mapper.AdminMapper;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/room")
public class RoomController extends BaseController{
    private final RoomConverter roomConverter;
    private final AdminMapper adminMapper;

    /**
     * 获取所有房间信息 搜索房间信息
     * @return
     */
//    @Cacheable(cacheNames = "room",keyGenerator = "keyGenerator",condition="#type != null")
    @RequiresPermissions({"room:list"})
    @GetMapping("/list")
    @Log
    public CommonResult getOrSearchRoom(String type, String data) {
        Page page = roomService.page(getPage(), new QueryWrapper<Room>().like(StrUtil.isNotBlank(type), type, data).orderBy(true, true, "room_no"));
        page.setRecords(roomConverter.toListRoomVO(page.getRecords()));
        return CommonResult.success(page);
    }

    /**
     * 根据房间类型id 获取所有可用房间的编号
     * @return
     */
    @RequiresPermissions({"room:list"})
    @GetMapping("/getFreeRoomIdsForRoomTypeId")
    public CommonResult getAllFreeRoomNo(String roomTypeId){
        log.error("------>roomTypeId:{}",roomTypeId);
        QueryWrapper<Room> wrapper = new QueryWrapper<>();
        wrapper.select("room_no")
                .eq(StrUtil.isNotBlank(roomTypeId),"room_type_id",roomTypeId)
                .eq("room_statue", RoomStatue.FREE.getStatue()).orderBy(true, true, "room_no");
        return CommonResult.success(roomService.listObjs(wrapper,s->(String)s));
    }

//    @RequiresPermissions({"room:list"})
//    @GetMapping("/getRoomTypeForRoomTypeId")
//    public CommonResult getRoomTypeForRoomTypeId(Integer roomTypeId){
//        QueryWrapper<Room> wrapper = new QueryWrapper<>();
//        wrapper.select("room_no")
//                .eq("id",roomTypeId)
//                .eq("room_statue", RoomStatue.FREE.getStatue()).orderBy(true, true, "room_no");
//        return CommonResult.success(roomService.listObjs(wrapper,s->(String)s));
//    }

    /**
     * 添加房间  自动设置room_no
     * @param roomVO
     * @return
     */
    @RequiresPermissions({"room:add"})
    @PostMapping("/add")
    @Log
    public CommonResult addRoom(@RequestParam("roomImage") MultipartFile[] fileList,@Validated RoomVO roomVO,
                                @RequestParam("roomType")String roomType){
        roomService.addRoom(fileList,roomVO,roomType);
        return CommonResult.success();
    }


    /**
     * 更新房间信息
     * @param roomVO
     * @return
     */
    @RequiresPermissions({"room:update"})
    @PostMapping("/update")
    @Log
    public CommonResult updateRoom(@RequestParam(value = "roomImage",required = false) MultipartFile[] fileList,@Validated RoomVO roomVO){
//        roomService.judgeRoomStatue(roomVO);
        Room room = roomConverter.toRoom(roomVO);
        if (fileList!=null){//存在需要保存的图片
            //删除
            minioTool.deleteBatch(room.getRoomFloor(),room.getRoomNo());
            String s = minioTool.saveBatchRoomImage(roomVO.getRoomFloor(), roomVO.getRoomNo(), fileList);
            if (StrUtil.isNotBlank(room.getRoomImages()))
                room.setRoomImages(room.getRoomImages() + "|" + s);
            else
                room.setRoomImages(s);
            if ((roomService.updateById(room)))
                return CommonResult.success();
        }
        if ((roomService.updateById(room)))
            return CommonResult.success();
        return CommonResult.fail();
    }


    /**
     * 批量删除房间
     * @return
     */
    @RequiresPermissions({"room:delete"})
    @PostMapping("/batch/delete")
    @Log
    public CommonResult bathDeleteRoom(@RequestBody Integer[] roomIds){
        if (roomService.removeBatchByIds(Arrays.asList(roomIds)))
            return CommonResult.success();
        return CommonResult.fail();
    }

    /**
     * 批量下架房间
     * @return
     */
    @RequiresPermissions({"room:update"})
    @PostMapping("/batch/down")
    @Log
    public CommonResult bathDownRoom(@RequestBody Integer[] roomIds){
        List<Room> rooms = Arrays.stream(roomIds).map(s -> (Room) new Room()
                .setRoomStatue(RoomStatue.OFF)
                .setId(s)).collect(Collectors.toList());
        if (roomService.updateBatchById(rooms))
            return CommonResult.success();
        return CommonResult.fail();
    }

    /**
     * 获取所有楼层
     * @return
     */
    @RequiresPermissions({"room:list"})
    @GetMapping("/floorList")
    public CommonResult getAllFloor(){
        return CommonResult.success(roomService.listObjs(new QueryWrapper<Room>().select("DISTINCT room_floor").orderByAsc("room_floor"), String::valueOf));
    }


    /**
     * 根据订单的orderRoomNo获取房间数据
     * @return
     */
    @RequiresPermissions({"room:list"})
    @GetMapping("/getRoomByOrderRoomNo/{roomNo}")
    public CommonResult getRoomByOrderRoomNo(@PathVariable String roomNo){
        RoomVO roomVO = roomConverter.toRoomVO(roomService.getOne(new QueryWrapper<Room>().eq("room_no", roomNo)));
        return CommonResult.success(roomVO);
    }
}
